﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EchoFramework
{
    /// <summary>
    /// 逻辑模块单例管理器
    /// </summary>
    public class LogicModuleManager : Singleton<LogicModuleManager>
    {
        /// <summary>
        /// 已启动的LogicModuleBase字典
        /// key：LogicModule具体类型FullName
        /// value: LogicModule具体对象
        /// </summary>
        private Dictionary<string, LogicModuleBase> logicModuleDict;


        /// <summary>
        /// 逻辑模块单例初始化
        /// </summary>
        public override void OnInit()
        {
            base.OnInit();
            logicModuleDict = new Dictionary<string, LogicModuleBase>();
        }

        public override void OnUpdate()
        {
            base.OnUpdate();
            foreach (var module in logicModuleDict)
            {
                module.Value.OnUpdate();
            }
        }

        /// <summary>
        /// 获取对应逻辑Module对象
        /// </summary>
        /// <typeparam name="T">泛型对象</typeparam>
        /// <returns>泛型对象</returns>
        public T GetLogicModule<T>() where T: LogicModuleBase, new()
        {
            string keyName = typeof(T).FullName;
            if(logicModuleDict.TryGetValue(keyName, out LogicModuleBase module))
            {
                return module as T;
            }
            T logicModule = new T();
            logicModule.OnInit();
            logicModuleDict.Add(keyName, logicModule);
            return logicModule;
        }
    }
}
